// pages/mine/room_register/steps_two/steps_two.js
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast'
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog'
const utils = require('../../../../utils/util.js')
const app = getApp()
const log = new app.appLogs()
const http = new app.appHttp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        numList: [{
            name: '实名登记'
        }, {
            name: '入住房间'
        }, {
            name: '物业审核'
        }, {
            name: '登记完成'
        },],
        num: 1,
        currentDate: new Date().getTime(),
        minDate: new Date().getTime(),
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            } else if (type === 'month') {
                return `${value}月`;
            }
            return value;
        },
        date: null,
        textareaShow: true,
        //联系电话
        phoneShow: false,
        phone: null,
        //小区
        community: null,
        communityShow: false,
        communityActions: [],
        columns: [{values: ['']}, {values: ['']}, {values: ['']}, {values: ['']}],
        address: null,
        addressTitle: null,
        roomId: null,
        //居住地址
        liveAddress: null,
        liveAddressShow: false,
        liveAddressActions: [],
        //楼栋
        liveBuilding: null,
        liveBuildingList: [],
        //单元
        liveCell: null,
        liveCellList: [],
        //居住类型
        liveType: null,
        liveTypeShow: false,
        liveTypeActions: [
            {name: '户籍', type: 1},
            {name: '流动', type: 0}
        ],
        //是否流动
        isFlow: false,
        //流动原因
        flowText: '',
        //与户主关系
        relationship: null,
        relationshipShow: false,
        relationshipActions: [],
        //是否租客
        isTenantry: false,
        //租赁到期时间
        expiryDate: null,
        expiryDateShow: false,
        expiryDateActions: [],
        //文件
        expiryFile: null,
        fileList: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getPeopleInfo()
    },

    /**
     * 获取居民详情
     */
    getPeopleInfo: function () {
        http.get('people_info/people', {
            people_id: app.globalData.userInfo.people_id
        }).then(res => {
            if (res.data.code === http.REQUEST_OK) {
                this.setData({
                    phoneShow: res.data.data.phone == null || res.data.data.phone.length <= 0
                })
            }
        })
    },

    /**
     * 联系电话
     * @param e
     */
    onPhone: function (e) {
        this.setData({
            phone: e.detail.value
        })
    },

    /**
     * 小区
     * @param e
     */
    onCommunity: function (e) {
        this.setData({
            communityShow: true,
            textareaShow: false,
        })
        http.get('yard/select/area_code', {
            area_code: app.globalData.areaCode
        }).then(res => {
            if (res.data.code === http.REQUEST_OK) {
                let data = []
                res.data.data.forEach(item => {
                    data.push({
                        name: item.yard_name,
                        id: item.yard_id
                    })
                })
                this.setData({
                    communityActions: data
                })
            } else {
                log.e(JSON.stringify(res))
            }
        }, err => {
            log.e(JSON.stringify(err))
        })

    },
    /**
     * 小区选择
     * @param e
     */
    onSheetCommunity: function (e) {
        const data = e.detail
        this.setData({
            community: data,
            communityShow: false
        })
    },

    /**
     * 居住地址
     * @param e
     */
    onLiveAddress: function (e) {
        if (this.data.community === null) {
            Toast.fail('请先选择小区')
            return
        }
        const yardId = this.data.community.id
        this.setData({
            textareaShow: false,
            liveAddressShow: true
        })
        http.get('building/select/' + yardId, {}).then(res => {
            if (res.data.code === http.REQUEST_OK) {
                this.setData({
                    liveBuildingList: res.data.data,
                })
                let data = [{
                    text: '请选择',
                    id: null,
                    index: 0
                }]
                res.data.data.forEach((item, index) => {
                    data.push({
                        text: item.building_name,
                        id: item.building_id,
                        index: index + 1,
                    })
                })
                this.data.columns[0].values = data
                this.setData({
                    columns: this.data.columns
                })
            } else {
                log.e(JSON.stringify(res))
            }
        }, err => {
            log.e(JSON.stringify(err))
        })
    },
    /**
     * 居住地址选择
     * @param e
     */
    onLiveAddressChange: function (e) {
        const {picker, value, index} = e.detail;
        if (index === 0) {
            if (value[index].index > 0) {
                http.get('cell/select/' + value[index].id, {}).then(res => {
                    if (res.data.code === http.REQUEST_OK) {
                        let data = [{
                            text: '请选择',
                            id: null,
                            index: 0
                        }]
                        res.data.data.forEach((item, index) => {
                            data.push({
                                text: item.cell_name,
                                id: item.cell_id,
                                index: index + 1
                            })
                        })
                        this.data.columns[1].values = data
                        this.setData({
                            columns: this.data.columns
                        })
                    } else {
                        log.l(JSON.stringify(res))
                    }
                }, err => {
                    log.e(JSON.stringify(err))
                })
            } else {
                this.data.columns[1].values = ['']
                this.data.columns[2].values = ['']
                this.data.columns[3].values = ['']
                this.setData({
                    columns: this.data.columns
                })
            }
        } else if (index === 1) {
            if (value[index].index > 0) {
                http.get('room/select/floor/' + value[index].id, {}).then(res => {
                    if (res.data.code === http.REQUEST_OK) {
                        let data = [{
                            text: '请选择',
                            id: null,
                            index: 0
                        }]
                        res.data.data.forEach((item, index) => {
                            data.push({
                                text: item.floor_num + '楼',
                                id: item.cell_id,
                                floor_num: item.floor_num,
                                index: index + 1
                            })
                        })
                        this.data.columns[2].values = data
                        this.setData({
                            columns: this.data.columns
                        })
                    } else {
                        log.l(JSON.stringify(res))
                    }
                }, err => {
                    log.e(JSON.stringify(err))
                })
            } else {
                this.data.columns[2].values = ['']
                this.data.columns[3].values = ['']
                this.setData({
                    columns: this.data.columns
                })
            }
        } else if (index === 2) {
            if (value[index].index > 0) {
                const cell_id = value[index].id
                const floor_num = value[index].floor_num
                http.get('room/select/room', {
                    cell_id: cell_id,
                    floor_num: floor_num
                }).then(res => {
                    if (res.data.code === http.REQUEST_OK) {
                        let data = [{
                            text: '请选择',
                            id: null,
                            index: 0
                        }]
                        res.data.data.forEach((item, index) => {
                            data.push({
                                text: item.room_name,
                                id: item.room_id,
                                name: item.room_full_name,
                                index: index + 1
                            })
                        })
                        this.data.columns[3].values = data
                        this.setData({
                            columns: this.data.columns
                        })
                    } else {
                        log.l(JSON.stringify(res))
                    }
                }, err => {
                    log.e(JSON.stringify(err))
                })
            } else {
                this.data.columns[3].values = ['']
                this.setData({
                    columns: this.data.columns
                })
            }
        } else if (index === 3) {
            if (value[index].index > 0) {
                this.data.address = value
                this.setData({
                    roomId: value[index].id,
                    addressTitle: value[index].name
                })
            } else {
                this.data.address = null
                this.setData({
                    addressTitle: null
                })
            }
        }
    },

    /**
     * 选择居住地址确认
     * @param e
     */
    onAddressConfirm: function (e) {
        if (this.data.addressTitle === null) {
            Toast.fail('请选择房间号')
        } else {
            this.setData({
                textareaShow: true,
                liveAddressShow: false
            })
        }
    },

    /**
     * 居住类型
     * @param e
     */
    onLiveType: function (e) {
        this.setData({
            textareaShow: false,
            liveTypeShow: true
        })
    },
    /**
     * 居住类型选择
     * @param e
     */
    onSheetLiveType: function (e) {
        const data = e.detail
        this.setData({
            liveType: data
        })
        if (data.type === 1) {
            this.setData({
                isFlow: false
            })
        } else {
            this.setData({
                isFlow: true
            })
        }
    },

    /**
     * 流动原因
     * @param e
     */
    onFlowDesc: function (e) {
        this.setData({
            flowText: e.detail.value
        })
    },

    /**
     * 与户主关系
     * @param e
     */
    onRelationship: function (e) {
        http.get('dic/getDicByName', {
            name: "D0006"
        }).then(res => {
            this.data.relationshipActions = []
            res.data.data.forEach(item => {
                this.data.relationshipActions.push({
                    name: item.dicValue,
                    flag: item.flag,
                })
            })
            this.setData({
                relationshipActions: this.data.relationshipActions,
                textareaShow: false,
                relationshipShow: true
            })
        }, err => {
            Toast.fail("网络异常")
        })

    },
    /**
     * 与户主关系选择
     * @param e
     */
    onSheetRelationship: function (e) {
        const data = e.detail
        this.setData({
            relationship: data
        })
        if (data.flag === "D0006_4") {
            this.setData({
                isTenantry: true
            })
        } else {
            this.setData({
                isTenantry: false
            })
        }
    },

    /**
     * 获取图片
     * @param e
     */
    onExpiryFile: function (e) {
        this.data.fileList = [{
            url: e.detail.file.path,
            status: 'uploading',
            message: '上传中',
        }]
        this.setData({
            fileList: this.data.fileList
        })
        http.upFile(e.detail.file.path, '/applet/rzzm').then(res => {
            if (res.code === http.REQUEST_OK) {
                this.data.expiryFile = res.data.url
                this.data.fileList = [{
                    url: res.data.url
                }]
                this.setData({
                    fileList: this.data.fileList
                })
            } else {
                log.l(JSON.stringify(res))
                this.data.fileList[0].status = 'failed'
                this.data.fileList[0].message = '上传失败'
                this.setData({
                    fileList: this.data.fileList
                })
            }
        }, err => {
            log.e(JSON.stringify(err))
            this.data.fileList[0].status = 'failed'
            this.data.fileList[0].message = '上传失败'
            this.setData({
                fileList: this.data.fileList
            })
        })
    },

    /**
     * 删除图片
     * @param e
     */
    onDeleteExpiryFile: function (e) {
        this.setData({
            fileList: []
        })
    },

    /**
     * 租赁到期时间
     * @param e
     */
    onExpiryDate: function (e) {
        this.setData({
            textareaShow: false,
            expiryDateShow: true
        })
    },

    /**
     * 租赁到期时间选择
     * @param e
     */
    onExpiryDateInput(e) {
        this.setData({
            currentDate: e.detail,
        });
        log.l(e.detail)
    },

    /**
     * 租赁到期时间 确定
     * @param e
     */
    onExpiryDateConfirm: function (e) {
        const date = utils.formatDate(this.data.currentDate / 1000, 'Y-M-D')
        this.setData({
            textareaShow: true,
            expiryDateShow: false,
            date: date
        })
    },

    /**
     * 关闭,取消按钮
     */
    onSheetClose: function (e) {
        this.setData({
            //小区
            communityShow: false,
            //居住地址
            liveAddressShow: false,
            //居住类型
            liveTypeShow: false,
            //与户主关系
            relationshipShow: false,
            //租赁到期时间
            expiryDateShow: false,
            //是否显示文本域
            textareaShow: true
        })
    },

    /**
     * 下一步
     * @param e
     */
    onNextSteps: function (e) {
        if (this.data.phoneShow) {
            if (this.data.phone == null || this.data.phone.length <= 0) {
                Toast.fail('联系电话不能为空')
                return
            }
            if (this.data.phone.length < 11) {
                Toast.fail('请输入正确的电话号码')
                return
            }
        }
        if (this.data.community == null) {
            Toast.fail('请选择小区')
            return
        }
        if (this.data.address == null) {
            Toast.fail('请选择居住地址')
            return
        }
        if (this.data.liveType == null) {
            Toast.fail('请选择居住类型')
            return
        }
        if (this.data.liveType.type === 0) {
            if (this.data.flowText.length <= 0) {
                Toast.fail('请输入流动原因')
                return
            }
        }
        if (this.data.relationship == null) {
            Toast.fail('请选择与户主关系')
            return
        }
        if (this.data.relationship.type === 3) {
            if (this.data.expiryFile == null) {
                Toast.fail('请上传租住证明')
                return
            }
            if (this.data.date == null) {
                Toast.fail('请选择到期时间')
                return
            }
        }
        const data = {
            people_id: app.globalData.userInfo.people_id,
            area_code: app.globalData.areaCode,
            yard_id: this.data.community.id,
            room_id: this.data.roomId,
            room_name: this.data.addressTitle,
            is_native: this.data.liveType.type,
            flow_reason: this.data.flowText,
            relation: this.data.relationship.flag,
            rent_deadline: this.data.date,
            img_url: this.data.expiryFile,
            phone: this.data.phone
        }
        log.e(JSON.stringify(data))
        http.postHeader('room/bind', {
            'Authorization': app.globalData.accessToken
        }, data).then(res => {
            if (res.data.code == 400) {
                Dialog.alert({
                    message: res.data.msg,
                }).then(() => {
                    // on close
                });
            }else {
                wx.navigateTo({
                    url: '../steps_three/steps_three'
                })
            }
        })

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})